// pages/progress/progress.js
import { ajax, src, util } from "../../utils/util.js";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    uqid:'',
    schedule: '0',//康复进度
    isPhoneAuth:false,
    islogin: false,//判断是否登录
    evaluation_time:"",
    ppid:"",
    goods_id:"",

    //loding 组件
     tips: '请稍后',
    show: false,
    animated: true
  },
  // redirectTo()
  /**
   * 生命周期函数--监听页面加载
   */

  toupimg:function(){
    wx.navigateTo({
      url: '/pages/upimg/upimg',
    })
  
  },
  tomyreserve(){
   
    wx.navigateTo({
      url: '/pages/myreserve/myreserve?currentTab=1',
    })
  
    
  },
  topay(){
    console.log("ssssssssss")
    if (this.data.schedule == 0) {
      wx.showToast({
        title: '请先去智能测评！',
        icon: 'none',
        duration: 1000
      })
    } else {
      var goods_id=this.data.goods_id
      wx.navigateTo({
        url: '/pages/reserveintro/reserveintro?goods_id=' + goods_id,
      })
    }
  },

  tozncp(){
    var that = this;
    console.log(this.data.uqid)
    console.log(this.data.phone)
    console.log(this.data.goods_id)

    ajax("/api/index/phone_add", {
      data: {
        uqid: this.data.uqid,
        phone: '',
        goods_id: 2
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'POST'
    }, res => {
      console.log(res);
      if (res.error == 0) {//获取进展 pid
        wx.setStorageSync("pid", res.data.pid)
        wx.navigateTo({
          url: '/pages/functionalimpairment/functionalimpairment',
        })
      } else if (res.error == 1) { //已有进展
        wx.setStorageSync("pid", res.data.pid)
        wx.navigateTo({
          url: '/pages/functionalimpairment/functionalimpairment',
        })
      }
    })


    // wx.switchTab({
    //   url: '/pages/index/index',
    // })

  },


 


  tocpkf:function(){
    wx.showToast({
      title: '请与您的康复顾问联系！',
      icon: 'none',
      duration: 1000
    })
  },

  tomyplan:function(){

    if (this.data.schedule>=1){
      wx.navigateTo({
        url: '/pages/myreserveplan/myreserveplan?ppid=' + this.data.ppid,
      })
    }
    
  },

  onLoad: function (options) {
    var uqid = wx.getStorageSync("uqid");
    // console.log("uqid="+uqid)
    this.setData({
      uqid: uqid
    });
    this.getProgress();
    var that = this;
    // 查看是否授权
    // console.log("查看是否授权")
    wx.getSetting({
      success(res) {
        // console.log(res)
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function (res) {
              that.setData({
                islogin:true
              })
              // console.log(res.userInfo)
            }
          })
        } else {
        }
      }
    })
  },
  //康复进展状态
  getProgress:function(){
    ajax("/api/index/user_patient", {
      data: {
        uqid: this.data.uqid,

      },
      header: {
        'Accept': 'application/json', // 默认值
      },
    }, res => {
      // console.log(res);
      if (res.error == 0) {
        //康复进度(0 - 没有找到进展 1 - 智能评测 2 - 线上预约 3 - 线下评测 4 - 康复方案 5 - 病例)
        console.log(res.data)
        console.log("aaaaaaaaaaaaaaaaaaaaa")
        this.setData({
          schedule: res.data.schedule,
          evaluation_time: res.data.evaluation_time,
          ppid: res.data.pid,
          goods_id: res.data.goods_id
        });

        wx.setStorageSync("ppid", res.data.pid)

        wx.setStorageSync("pid", res.data.pid)
        
      }
    })
  },


  //获取个人信息
  getInfo: function (uqid) {
    ajax("/api/index/user_info", {
      data: {
        uqid: uqid,
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
    }, res => {
      // console.log(res);
      if (res.error == 0) {

        this.setData({
          userinfo: res.data,
          uqid: uqid,
          islogin: true
        });
      }
    })
  },


  addyaoqing: function () {
    ajax("/api/index/distribution", {
      data: {
        uqid: wx.getStorageSync('uqid'),
        yq_uqid: wx.getStorageSync('yq_uqid')
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'post'
    }, res => {
      console.log(res)
      if (res.error == 0) {
        // wx.showToast({
        //   title: '分销成功',
        //   icon: 'none',
        //   duration: 2000
        // })
      }
    })
  },

  //立即获取智能康复计划  && 授权
  bindGetUserInfo(e) {
    var that = this;
    console.log(e.detail.userInfo)
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var code = wx.getStorageSync("code");
      ajax('/api/index/login', {
        data: {
          js_code: code,
          nickname: e.detail.userInfo.nickName,
          avatar: e.detail.userInfo.avatarUrl
        },
        header: {
          'Accept': 'application/json', // 默认值
        },
      }, res => {
        console.log(res)
        if (res.error == 0) {
          wx.setStorageSync("uqid", res.data.uqid)

          that.setData({
            uqid: res.data.uqid,
            session_key: res.data.session_key
          });
          this.isPhone();
          this.getProgress()

          if (wx.getStorageSync('yq_uqid')) {
            if (wx.getStorageSync('yq_uqid') != this.data.uqid) {
              this.addyaoqing()
            } else {
              console.log('是本人')
            }
          }


        } else if (res.error == 4003) { //重复授权
          this.isPhone();
          this.getProgress()

          if (wx.getStorageSync('yq_uqid')) {
            if (wx.getStorageSync('yq_uqid') != this.data.uqid) {
              this.addyaoqing()
            } else {
              console.log('是本人')
            }
          }
        }
      })
    } else {
      wx.showToast({
        title: '请先授权！',
        icon: 'none',
        duration: 2000
      })

    }
  },

  //判断是否授权手机号
  isPhone: function () {
    var that = this;
    var tel = wx.getStorageSync("tel");
    if (tel == undefined || tel == '') { //用户没有授权手机号
      that.setData({
        isPhoneAuth: true
      });
    } else { //用户已经授权手机号
      that.setData({
        isPhoneAuth: false
      });
      // this.getTelAdd();

    }
  },

  //授权手机号
  getPhoneNumber(e) {
    this.setData({
      isPhoneAuth: false
    })
    if (e.detail.encryptedData) {
      ajax("/api/index/phone_decrypt", {
        data: {
          session: this.data.session_key,
          iv: e.detail.iv,
          encryptedData: e.detail.encryptedData
        },
        header: {
          'Accept': 'application/json', // 默认值
        },
        method: 'POST'
      }, res => {
        // console.log(res);
        if (res.error == 0) {
          var tel = res.data.phoneNumber;
          wx.setStorageSync("tel", tel)
          this.getTelAdd();
        }
      })

    } else {
      this.getInfo(this.data.uqid);
      this.setData({
        islogin: true
      })
    }
  },
  //拒绝授权手机号
  refuseUserInfo: function () {
    this.getInfo(this.data.uqid);
    this.setData({
      isPhoneAuth: false,
      islogin: true
    });
  },
  //授权手机号提交
  getTelAdd: function () {
    var tel = wx.getStorageSync("tel");
    ajax("/api/index/phone_wx_sq_add", {
      data: {
        uqid: this.data.uqid,
        phone: tel,
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'POST'
    }, res => {
      // console.log(res);
      if (res.error == 0) {//获取进展 pid
        this.getInfo(this.data.uqid);
      }
    })
  },


  // progress1:function(){
  //   wx.switchTab({
  //     url: '/pages/index/index',
  //   })
  // },
  progress2: function () {
    wx.navigateTo({
      url: '/pages/myreserveplan/myreserveplan',
    })
  },
  //上传病历
  start:function(){
    
    this.setData({
      show: true
    })
    
  },
  end:function(){
    this.setData({
      show: false
    })
  },

  uploadMedical:function(){
    var uqid = this.data.uqid;
    console.log(uqid)
    var that=this
    wx.showActionSheet({
      itemList: ['从相册选取', '拍照'],
      success(res) {
        console.log(res.tapIndex)
        var index = res.tapIndex;
        if (index == 0) {
          wx.chooseImage({

            count: 9,
            sizeType: ['original', 'compressed'],
            sourceType: ['album'],
            success(res) {
              console.log(res)

              that.start()

              // tempFilePath可以作为img标签的src属性显示图片
              const tempFilePaths = res.tempFilePaths;
              console.log(tempFilePaths)

              wx.uploadFile({
                url: src + '/api/index/outers_add', 
                filePath: tempFilePaths[0],
                name: 'image',
                header: { "Content-Type": "multipart/form-data" },
                formData: {
                  uqid:uqid,
                  name: '我的病历'
                },
                success(resU) {
                  console.log(resU)
                  console.log(JSON.parse(resU.data))
                  if (JSON.parse(resU.data).error == 0) {
                    wx.showToast({
                      title: '上传成功,请到我的病历中查看！',
                      icon: 'none',
                      duration: 1000
                    })

                    that.end()
                  }

                }
              })
            }
          })
        } else if (index == 1) {
          wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['camera'],
            success(res) {
              console.log(res)
              // tempFilePath可以作为img标签的src属性显示图片
              const tempFilePaths = res.tempFilePaths;
              wx.uploadFile({
                url: src + '/api/index/outers_add', 
                filePath: tempFilePaths[0],
                name: 'image',
                header: { "Content-Type": "multipart/form-data" },
                formData: {
                  uqid: uqid,
                  name:'我的病历'
                },
                success(resU) {
                  console.log(resU)
                  if (JSON.parse(resU.data).error == 0) {
                    wx.showToast({
                      title: '上传成功,请到我的病历中查看！',
                      icon: 'none',
                      duration: 1000
                    })
                  }
                }
              })
            }
          })
        }

      },
      fail(res) {
        console.log(res.errMsg)
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var uqid = wx.getStorageSync("uqid");
    console.log("uqid=" + uqid)
    this.setData({
      uqid: uqid
    });
    this.getProgress();
    var that = this;
    // 查看是否授权
    console.log("查看是否授权")
    wx.getSetting({
      success(res) {
        console.log(res)
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function (res) {
              that.setData({
                islogin: true
              })
              console.log(res.userInfo)
            }
          })
        } else {
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  // onPullDownRefresh: function () {
  //   this.getProgress();
  //   wx.stopPullDownRefresh();
  // },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})